package net.sk.china.city.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import net.sk.china.city.domain.ArDonateSource;
import net.sk.china.city.domain.ArDonationMapping;
import net.sk.china.city.domain.ArDonations;
import net.sk.china.city.domain.dto.donate.DonateSourceDTO;
import net.sk.china.city.domain.vo.AddDonate;
import net.sk.china.city.domain.vo.ArDonateVO;
import net.sk.china.city.domain.vo.DonateVO;
import net.sk.china.city.domain.vo.UpdateDonateVO;
import net.sk.china.city.mapper.ArDonateSourceMapper;
import net.sk.china.city.mapper.ArDonationMappingMapper;
import net.sk.china.city.mapper.ArDonationsMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import net.sk.china.city.domain.dto.TableDataInfo;
import net.sk.china.city.utils.DateUtils;
import net.sk.china.city.utils.SecurityUtils;
import net.sk.china.common.exception.ServiceException;
import net.sk.china.city.utils.PlatformIdHolder;
import lombok.SneakyThrows;
import net.sk.china.city.service.IArDonateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.sk.china.city.mapper.ArDonateMapper;
import net.sk.china.city.domain.ArDonate;
import org.springframework.transaction.annotation.Transactional;

/**
 * 捐赠列表Service业务层处理
 * 
 * @author gxf
 * @date 2024-04-07
 */
@Service
public class ArDonateServiceImpl implements IArDonateService
{
    @Autowired
    private ArDonateMapper arDonateMapper;

    @Autowired
    private ArDonationsMapper arDonationsMapper;

    @Autowired
    private ArDonateSourceMapper arDonateSourceMapper;


    @Autowired
    private ArDonationMappingMapper arDonationMappingMapper;

    /**
     * 查询捐赠列表
     * 
     * @param id 捐赠列表主键
     * @return 捐赠列表
     */
    @SneakyThrows
    @Override
    public ArDonateVO selectArDonateById(Long id)
    {
        ArDonate arDonate = arDonateMapper.selectArDonateById(id);
        ArDonateVO arDonateVO = new ArDonateVO();
        if (arDonate == null){
            return arDonateVO;
        }
        List<ArDonations> donations = arDonationsMapper.selectList(new QueryWrapper<ArDonations>().eq("donate_id", id));
        arDonateVO.setId(arDonate.getId());
        arDonateVO.setIndexImg(arDonate.getIndexImg());
        arDonateVO.setDonationNumber(arDonate.getDonationNumber());
        arDonateVO.setRemark(arDonate.getRemark());
        arDonateVO.setArDonations(donations);
        List<Long> dataList = new ObjectMapper().readValue(arDonate.getSourceId(), new TypeReference<List<Long>>() {});
        List<DonateSourceDTO> arDonateSources = new ArrayList<>();
        for (Long sourceId : dataList) {
            ArDonateSource arDonateSource = arDonateSourceMapper.selectById(sourceId);
            DonateSourceDTO donateSource = new DonateSourceDTO();
            donateSource.setId(arDonateSource.getId());
            donateSource.setDonateName(arDonateSource.getDonateName());
            arDonateSources.add(donateSource);
        }
        arDonateVO.setArDonateSources(arDonateSources);
        return arDonateVO;
    }

    /**
     * 查询捐赠列表列表
     *
     * @param arDonate 捐赠列表
     * @return 捐赠列表
     */
    @Override
    @SneakyThrows
    public TableDataInfo selectArDonateList(ArDonate arDonate)
    {
        List<DonateVO> arDonateVOList = new ArrayList<>();
        arDonate.setPlatformId(PlatformIdHolder.getPlatformId());
        List<ArDonate> arDonates = arDonateMapper.selectArDonateList(arDonate);
        for (ArDonate donate : arDonates) {
            DonateVO donateVO = new DonateVO();
            donateVO.setDonationNumber(donate.getDonationNumber());
            donateVO.setTotalPrice(donate.getTotalPrice());
            donateVO.setIndexImg(donate.getIndexImg());
            donateVO.setId(donate.getId());
            List<Long> dataList = new ObjectMapper().readValue(donate.getSourceId(), new TypeReference<List<Long>>() {});
            List<String> sourceName = new ArrayList<>();
            for (Long sourceId : dataList) {
                ArDonateSource arDonateSource = arDonateSourceMapper.selectById(sourceId);
                sourceName.add(arDonateSource.getDonateName());
            }
            donateVO.setSourceName(sourceName);
            arDonateVOList.add(donateVO);
        }
        PageInfo<ArDonate> arDonatePageInfo = new PageInfo<>(arDonates);
        PageInfo<DonateVO> donateVOPageInfo = new PageInfo<>(arDonateVOList);
        donateVOPageInfo.setTotal(arDonatePageInfo.getTotal());
        TableDataInfo tableDataInfo =new TableDataInfo<>();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(donateVOPageInfo.getTotal());
        tableDataInfo.setRows(donateVOPageInfo.getList());
        return tableDataInfo;
    }

    /**
     * 新增捐赠列表
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int insertArDonate(AddDonate addDonate)
    {
//        String result = PinyinUtil.getFirstLetter(addDonate.getDonateName(),"");
        List<DonateSourceDTO> arDonateSources = addDonate.getArDonateSources();
        List<String> sourceId = new ArrayList<>();
        if(arDonateSources != null){
            for(DonateSourceDTO donateSourceDTO : arDonateSources){
                sourceId.add(donateSourceDTO.getId().toString());
            }
        }
        ArDonate arDonate = new ArDonate();
        arDonate.setDonationNumber(IdUtil.getSnowflakeNextIdStr());
        arDonate.setIndexImg(addDonate.getIndexImg());
        arDonate.setCreateBy(SecurityUtils.getUsername());
        arDonate.setCreateTime(LocalDate.now());
        arDonate.setSourceId(JSON.toJSONString(sourceId));
        arDonate.setRemark(addDonate.getRemark());
        arDonate.setPlatformId(PlatformIdHolder.getPlatformId());
        int i = arDonateMapper.insertArDonate(arDonate);
        if(i != 1){
            throw new ServiceException("新增失败",409);
        }
        if(arDonateSources != null){
            for(DonateSourceDTO donateSourceDTO : arDonateSources){
                ArDonationMapping arDonationMapping = new ArDonationMapping();
                arDonationMapping.setDonateId(arDonate.getId());
                arDonationMapping.setSourceId(donateSourceDTO.getId());
                int insert = arDonationMappingMapper.insert(arDonationMapping);
                if (insert != 1) {
                    throw new ServiceException("新增失败", 409);
                }
            }
        }
        List<ArDonations> arDonationsList = addDonate.getArDonations();
        BigDecimal totalPriceSum = BigDecimal.ZERO; // 初始化总和为0
        if (arDonationsList != null) {
            for (ArDonations arDonations : arDonationsList) {
                ArDonations donations = new ArDonations();
                donations.setMaterialName(arDonations.getMaterialName());
                donations.setSpecifications(arDonations.getSpecifications());
                donations.setItemNumber(arDonations.getItemNumber());
                donations.setMonovalent(arDonations.getMonovalent());
                donations.setTotalPrice(arDonations.getMonovalent().multiply(BigDecimal.valueOf(arDonations.getItemNumber())));
                donations.setDonateId(arDonate.getId());
                int i1 = arDonationsMapper.insertArDonations(donations);
                if (i1 != 1) {
                    throw new ServiceException("新增失败", 409);
                }

                totalPriceSum = totalPriceSum.add(donations.getTotalPrice()); // 将当前 ArDonations 对象的 TotalPrice 添加到总和中
            }
        }
        ArDonate update = new ArDonate();
        update.setId(arDonate.getId());
        update.setTotalPrice(totalPriceSum);
        int i1 = arDonateMapper.updateArDonate(update);
        if(i1 != 1){
            throw new ServiceException("新增失败",409);
        }
        return 1;
    }

    /**
     * 修改捐赠列表
     * @return 结果
     */
    @Override
    @Transactional
    public int updateArDonate(UpdateDonateVO updateDonateVO)
    {
        List<DonateSourceDTO> arDonateSources = updateDonateVO.getArDonateSources();
        List<String> sourceId = new ArrayList<>();
        if(arDonateSources != null){
            for(DonateSourceDTO donateSourceDTO : arDonateSources){
                sourceId.add(donateSourceDTO.getId().toString());
            }
        }
        if(!JSON.toJSONString(sourceId).equals(arDonateMapper.selectById(updateDonateVO.getId()).getSourceId())){
            int i = arDonationMappingMapper.delete(new QueryWrapper<ArDonationMapping>().eq("donate_id", updateDonateVO.getId()));
            if (i < 1) {
                throw new ServiceException("修改失败", 409);
            }
            if(arDonateSources != null){
                for(DonateSourceDTO donateSourceDTO : arDonateSources){
                    ArDonationMapping arDonationMapping = new ArDonationMapping();
                    arDonationMapping.setDonateId(updateDonateVO.getId());
                    arDonationMapping.setSourceId(donateSourceDTO.getId());
                    int insert = arDonationMappingMapper.insert(arDonationMapping);
                    if (insert != 1) {
                        throw new ServiceException("修改失败", 409);
                    }
                }
            }
        }
        ArDonate arDonate = new ArDonate();
        arDonate.setId(updateDonateVO.getId());
        arDonate.setIndexImg(updateDonateVO.getIndexImg());
        arDonate.setRemark(updateDonateVO.getRemark());
        arDonate.setUpdateBy(SecurityUtils.getUsername());
        arDonate.setUpdateTime(LocalDate.now());
        arDonate.setSourceId(JSON.toJSONString(sourceId));
        int i = arDonateMapper.updateArDonate(arDonate);
        if(i != 1){
            throw new ServiceException("修改失败",409);
        }
        List<ArDonations> arDonationsList = updateDonateVO.getArDonations();
        BigDecimal totalPriceSum = BigDecimal.ZERO; // 初始化总和为0
        if (arDonationsList != null) {
            for (ArDonations arDonations : arDonationsList) {
                ArDonations donations = new ArDonations();
                donations.setMaterialName(arDonations.getMaterialName());
                donations.setSpecifications(arDonations.getSpecifications());
                donations.setItemNumber(arDonations.getItemNumber());
                donations.setMonovalent(arDonations.getMonovalent());
                donations.setTotalPrice(arDonations.getMonovalent().multiply(BigDecimal.valueOf(arDonations.getItemNumber())));
                donations.setDonateId(arDonate.getId());
                if(arDonations.getId() != null){
                    donations.setId(arDonations.getId());
                    int i1 = arDonationsMapper.updateById(donations);
                    if (i1 != 1) {
                        throw new ServiceException("修改失败", 409);
                    }
                }else {
                    int i1 = arDonationsMapper.insert(donations);
                    if (i1 != 1) {
                        throw new ServiceException("修改失败", 409);
                    }
                }


                totalPriceSum = totalPriceSum.add(donations.getTotalPrice()); // 将当前 ArDonations 对象的 TotalPrice 添加到总和中
            }
        }
        ArDonate update = new ArDonate();
        update.setId(arDonate.getId());
        update.setTotalPrice(totalPriceSum);
        int i1 = arDonateMapper.updateArDonate(update);
        if(i1 != 1){
            throw new ServiceException("修改失败",409);
        }
        return 1;
    }

    /**
     * 批量删除捐赠列表
     * 
     * @param ids 需要删除的捐赠列表主键
     * @return 结果
     */
    @Override
    public int deleteArDonateByIds(Long[] ids)
    {
//        return arDonateMapper.deleteArDonateByIds(ids);
        for (Long id : ids){
            int i = arDonateMapper.deleteArDonateById(id);
            if(i != 1){
                throw new ServiceException("删除失败",409);
            }
        }

        return 1;
    }

    /**
     * 删除捐赠列表信息
     * 
     * @param id 捐赠列表主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteArDonateById(Long id)
    {
        int i = arDonateMapper.deleteArDonateById(id);
        if(i != 1){
            throw new ServiceException("删除失败",409);
        }
//        int i = arDonateMapper.deleteArDonateById(id);
//        if(i != 1){
//            throw new ServiceException("删除失败",409);
//        }
//        int i1 = arDonationsMapper.delete(new QueryWrapper<ArDonations>().eq("donate_id", id));
//        if(i1 == 0){
//            throw new ServiceException("删除失败",409);
//        }
        return 1;
    }
}
